const fs = require("fs");
const path = require("path");
const Router = require("koa-router");
const router = new Router();
const root_path = path.resolve(__dirname, "./");
/**
 * 遍历文件夹下面的所有文件，推入路由中，
 *
 * @param {*} path
 * @param {*} entry_name
 */
function pushRouterFromDir(dir_path, expect_file_name) {
  fs.readdirSync(dir_path, { withFileTypes: true }).forEach(file => {
    if (file.isDirectory()) {
      const sub_path = path.resolve(__dirname, dir_path, file.name);
      pushRouterFromDir(sub_path);
    } else {
      if (file.name !== expect_file_name) {
        // 获取当前目录，
        // 获取子目录
        const sub_path = path.resolve(__dirname, dir_path, file.name);
        // 获得相对路径
        const relative_path = path.relative(root_path, sub_path);
        const sub_router = require("./" + relative_path);
        if (sub_router.routes) {
          router.use(sub_router.routes(), sub_router.allowedMethods());
        }
      }
    }
  });
}
router.get("/shop", ctx => {
  ctx.redirect("/shop/index.html");
});

router.get("/admin", ctx => {
  ctx.redirect("/admin/index.html");
});

pushRouterFromDir(path.resolve(__dirname, "./"), "index.js");

module.exports = router;
